﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LPV_POS.Module;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Resources;
using System.Globalization;


namespace LPV_POS.mh_pos
{
    public partial class mh_dmcompany : DevExpress.XtraEditors.XtraForm
    {
        CultureInfo culture;
        xulyngaythangnam ngaythang;
        thuvien tv;
        DataTable tb;
        string[] s;
        object[] o;

        #region "Muti language"

        private void SetLanguage_banhang(string cultureName)
        {
            try
            {
                culture = CultureInfo.CreateSpecificCulture(cultureName);
                ResourceManager rm = new ResourceManager("LPV_POS.Muti_language.MyResource", typeof(mh_banhang6_PhuThu).Assembly);
                label1.Text = rm.GetString("tencongty", culture);
                label3.Text = rm.GetString("ngaythanhlap", culture);
                label6.Text = rm.GetString("dienthoai", culture);
                label5.Text = rm.GetString("fax", culture);
                label4.Text = rm.GetString("diachi", culture);
                label10.Text = rm.GetString("email", culture);
                bton_luu.Text = rm.GetString("luu", culture);
                label9.Text = rm.GetString("chude", culture);
                lbel_nguoinhan.Text = rm.GetString("nguoinhan", culture);
                label7.Text = rm.GetString("ten", culture); 
                lbel_nguoigoi.Text = rm.GetString("emailnguoigoi", culture);
                lbel_filedinhkem.Text = rm.GetString("filedinhkem", culture);

                bton_noidung.Text = rm.GetString("noidung", culture);
                bton_send.Text = rm.GetString("goi", culture);
                bton_cauhinh.Text = rm.GetString("cauhinh", culture);
                bton_thoat.Text = rm.GetString("thoat", culture);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Note");
            }

        }

        #endregion


        private DataTable f_selectdmcongty()
        {
            s = new string[] { "@FLAG", "@CHOOSE" };
            o = new object[] { 1, 1 };
            tv = new thuvien();
            tb = tv.SP_SelectDataTable("sp_mhcompany", s, o);
            return tb;
        }
        private DataTable f_selectdsendmail()
        {
            s = new string[] { "@FLAG", "@CHOOSE" };
            o = new object[] { 1, 2 };
            tv = new thuvien();
            tb = tv.SP_SelectDataTable("sp_mhcompany", s, o);
            return tb;
        }

        private int f_updatedmcompany(string tencongty, string tenviettat, 
            string ngaythanhlap, string dienthoai, string fax, 
            string diachi,string Email)
        {
            tv = new thuvien();
            s = new string[] { "@flag", "@TENCONGTY", "@TENVIETTAT", "@NGAYTHANHLAP_STR", "@DIENTHOAI", "@FAX", "@DIACHI","@EMAIL"};
            o = new object[] { 2, tencongty, tenviettat, ngaythanhlap, dienthoai, fax, diachi,Email};
            int ketqua = tv.SP_Update("sp_mhcompany", s, o);
            return ketqua;
        }

        private DataTable f_updatedmcongty()
        {
            s = new string[] { "@FLAG" };
            o = new object[] { 1 };
            tv = new thuvien();
            tb = tv.SP_SelectDataTable("sp_mhcompany", s, o);
            return tb;
        }
        public mh_dmcompany()
        {
            InitializeComponent();
            culture = CultureInfo.CurrentCulture;
        }


        private void bton_luu_Click(object sender, EventArgs e)
        {
            ngaythang = new xulyngaythangnam();
            int ketqua = 0;
            string tencongty = txt_tencongty.Text;
            string tenviettat = txt_tenviettat.Text;
            string ngaythanhlap = "";
            if (date_ngaythanhlap.Text == "")
                ngaythanhlap = "";
            else
                ngaythanhlap = ngaythang.chuyenngay(date_ngaythanhlap.Text);
            string dienthoai = txt_dienthoai.Text;
            string fax = txt_Fax.Text;
            string diachi = txt_diachi.Text;
            if (txtEmail.Text + "" != "")
            {
                if (!new cpublic().IsValidEmailAddress(txtEmail.Text))
                {
                    MessageBox_LPV.Show("Email không hợp lệ.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtEmail.Focus();
                    return;
                }
            }
            ketqua = f_updatedmcompany(tencongty, tenviettat, ngaythanhlap, dienthoai, fax, diachi,txtEmail.Text);
            if (ketqua == -1)
            {
                Mod_messagebox mess = new Mod_messagebox();
                mess.messagebox_pos("Thông báo", "Sửa không thành công thông tin công ty", loaithongbao.canhbao.GetHashCode());
                return;
            }
        }

        private void mh_dmcompany_Load(object sender, EventArgs e)
        {
            cpublic ocpublic = new cpublic();
            string str_lang = ocpublic.Registry_Get("mh_main_lang");
            if (str_lang == "")
                str_lang = "vi-VN";
            SetLanguage_banhang(str_lang);

            tb = new DataTable();
            tb = f_selectdmcongty();
            if (tb.Rows.Count > 0)
            {
                txt_tencongty.Text = tb.Rows[0]["TENCONGTY"] + "";
                txt_tenviettat.Text = tb.Rows[0]["TENVIETTAT"] + "";
                txt_diachi.Text = tb.Rows[0]["DIACHI"] + "";
                txt_dienthoai.Text = tb.Rows[0]["DIENTHOAI"] + "";
                txt_Fax.Text = tb.Rows[0]["FAX"] + "";
                //if (tb.Rows[0]["NGAYTHANHLAP"] + "" == "")
                //    date_ngaythanhlap.Text = DateTime.Now.ToString("dd/MM/yyyy");
                //else
                string ngay = tb.Rows[0]["NGAYTHANHLAP"] + "";
                if (ngay == "")
                    date_ngaythanhlap.Text = "";
                else
                    date_ngaythanhlap.Text = Convert.ToDateTime(ngay).ToString("dd/MM/yyyy");     //ngay.ToString("dd/MM/yyyy");
                txtEmail.Text = tb.Rows[0]["EMAIL"] + "";
            }
            //   txt_smtp.Text = "192.168.1.1"
        }

        #region "   f_sendmail"
        private Int16 f_sendmail(string mstpserver, int port, Boolean ssl, string tennguoigoi, string mailfrom, string password, string mailto, string chude, string noidung)
        {
            try
            {

                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(mailfrom, tennguoigoi, System.Text.Encoding.UTF8);
                msg.To.Add(mailto);        // msg.To là một collection, cho phép bạn gửi đến nhiều địa chỉ
                msg.Subject = chude;
                msg.Body = noidung;
                msg.Priority = MailPriority.High;
                if (txtAttachFile.Text != "")
                {
                    Attachment att = new Attachment(txtAttachFile.Text);
                    msg.Attachments.Add(att);

                }

                msg.SubjectEncoding = Encoding.UTF8;
                msg.BodyEncoding = Encoding.UTF8;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient();
                client.Credentials = new NetworkCredential(mailfrom, password);    // thay bằng username và password của bạn  

                client.Host = mstpserver;   //"smtp.gmail.com";
                client.Port = port;              //bắt buộc phải là cổng 587 
                client.EnableSsl = ssl;        //server của gmail yêu cầu kết nối SSL (Secure Socket Layer) để bảo vệ thông tin đăng nhập  
                //client.Send(msg);
                client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                object userstate = msg;
                client.SendAsync(msg, userstate);

                return 1;
            }
            catch (Exception ex)
            {
                string a = ex.ToString();
                return -1;
            }
        }
        #endregion

        #region "   Send_Email"
        public void Send_Email(string sSender, string sFrom, string sPass, string sTo, string sSubject, string sbody, string sAttachFile)
        {
            this.Cursor = Cursors.WaitCursor;
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(sFrom, sSender, System.Text.Encoding.UTF8);
            msg.To.Add(sTo);
            msg.Subject = sSubject;
            msg.Body = sbody;
            msg.Priority = MailPriority.High;
            if (sAttachFile.Trim() != "")
            {
                if (new FileInfo(sAttachFile).Exists)
                {
                    Attachment att = new Attachment(sAttachFile);
                    msg.Attachments.Add(att);
                }
            }
            msg.SubjectEncoding = Encoding.UTF8;
            msg.BodyEncoding = Encoding.UTF8;
            msg.IsBodyHtml = false;
            //
            SmtpClient client = new SmtpClient();
            #region "   SMTP Gmail"
            client.Credentials = new NetworkCredential(sFrom, sPass);    // thay bằng username và password của bạn  
            client.Host = "smtp.gmail.com";
            client.Port = 587;            //bắt buộc phải là cổng 587 
            #endregion

            #region "   SMTP Ymail"
            //client.Credentials = new NetworkCredential(sFrom, sPass);    // thay bằng username và password của bạn  
            //client.Host = "smtp.mail.yahoo.com";
            //client.Port = 645;
            #endregion

            client.EnableSsl = true;        //server của gmail yêu cầu kết nối SSL (Secure Socket Layer) để bảo vệ thông tin đăng nhập  
            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            object userstate = msg;
            client.SendAsync(msg, userstate);
            //
            
        }
        #endregion

        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.Cursor = Cursors.Default;
            String token = "Lý Phú Vinh Co.,Ltd";// (string)e.UserState;

            if (e.Cancelled)
            {
                MessageBox.Show("Gửi thất bại", token);
            }
            if (e.Error != null)
            {
                MessageBox.Show(e.Error + "", token);
            }
            else
            {
                MessageBox.Show("Gửi thành công", token);
            }
            ///////////////
            MailMessage msg = (MailMessage)e.UserState;
            if (msg != null)
                msg.Dispose();
        }
        private void bton_send_Click(object sender, EventArgs e)
        {
            string chude = txtsubject.Text;
            string mailgoi = txtfrom.Text;
            string tennguoigoi = txt_tennguoigoi.Text;
            string mailnhan = txtto.Text;
            string matma = txtpass.Text;

            #region "   Kiem Tra Hop Le"
            if (chude == "" || mailgoi == "" || tennguoigoi == "" || mailnhan == "" || matma == "")
            {
                Mod_messagebox mess = new Mod_messagebox();
                mess.messagebox_pos("Thông báo", "Vui lòng nhập đầy đủ thông tin?", loaithongbao.baoloi.GetHashCode());
                return;
            }
            cpublic ocpublic = new cpublic();
            if (ocpublic.IsValidEmailAddress(mailgoi) == false || ocpublic.IsValidEmailAddress(mailnhan) == false)
            {
                Mod_messagebox mess = new Mod_messagebox();
                mess.messagebox_pos("Thông báo", "Vui lòng nhập đúng cấu trúc địa chỉ mail?", loaithongbao.baoloi.GetHashCode());
                return;
            }
            #endregion

            //DataTable tb;
            //tb = f_selectdsendmail();
            //string smtp = tb.Rows[0]["SMTPSERVER"] + "";
            //string port_str = tb.Rows[0]["PORT"] + "";
            //int port = 0;
            //if (port_str != "")
            //    port = Convert.ToInt16(port_str);
            //Boolean ssl = false;
            //string ssl_str = tb.Rows[0]["SSL_"] + "";
            //if (ssl_str == "True")
            //    ssl = true;
            //else
            //    ssl = false;
            this.Send_Email(txt_tennguoigoi.Text, txtfrom.Text, txtpass.Text, txtto.Text, txtsubject.Text, txtbody.Text, txtAttachFile.Text);
            
            //Int16 ketqua = f_sendmail(smtp, port, ssl, txt_tennguoigoi.Text, txtfrom.Text, txtpass.Text, txtto.Text, txtsubject.Text, txtbody.Text);

            #region "   Thông báo kết quả"
            //if (ketqua == 1)
            //{
            //    Mod_messagebox mess = new Mod_messagebox();
            //    mess.messagebox_pos("Thông báo", "Gởi mail thành công", loaithongbao.thongtin.GetHashCode());
            //    return;
            //}

            //else
            //{
            //    Mod_messagebox mess = new Mod_messagebox();
            //    mess.messagebox_pos("Thông báo", "Gởi mail không thành công, xem lại đường truyền", loaithongbao.thongtin.GetHashCode());
            //    return;
            //}
            #endregion
        }


        private void lbel_filedinhkem_MouseHover(object sender, EventArgs e)
        {
            lbel_filedinhkem.ForeColor = System.Drawing.Color.Red;
        }

        private void lbel_filedinhkem_MouseLeave(object sender, EventArgs e)
        {
            lbel_filedinhkem.ForeColor = System.Drawing.Color.Black;
        }

        private void lbel_filedinhkem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                txtAttachFile.Text = dlg.FileName;
                lbel_tenfiledinhkem.Text = Path.GetFileName(dlg.FileName);

            }
        }

        private void bton_tencongty_Click(object sender, EventArgs e)
        {
            txt_tencongty.Text = new cpublic().loadformchu_point(300, 200);
        }

        private void bton_dienthoai_Click(object sender, EventArgs e)
        {
            txt_dienthoai.Text = new cpublic().loadformchu_point(300, 200);
        }

        private void bton_tenviettat_Click(object sender, EventArgs e)
        {
            txt_tenviettat.Text = new cpublic().loadformchu_point(300, 200);
        }

        private void bton_diachi_Click(object sender, EventArgs e)
        {
            txt_diachi.Text = new cpublic().loadformchu_point(300, 200);
        }

        private void bton_fax_Click(object sender, EventArgs e)
        {
            txt_Fax.Text = new cpublic().loadformchu_point(300, 200);
        }

        private void bton_chude_Click(object sender, EventArgs e)
        {
            txtsubject.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void bton_nguoinhan_Click(object sender, EventArgs e)
        {
            txtto.Text = new cpublic().loadformchu_point(200, 200);
        }


        private void bton_nguoigoi_Click(object sender, EventArgs e)
        {
            txtfrom.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void bton_tennguoigoi_Click(object sender, EventArgs e)
        {
            txt_tennguoigoi.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void bton_matma_Click(object sender, EventArgs e)
        {
            txtpass.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void bton_noidung_Click(object sender, EventArgs e)
        {
            txtbody.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void bton_thoat_Click(object sender, EventArgs e)
        {
            Mod_messagebox mess = new Mod_messagebox();
            mess.messagebox_pos("Thông báo", "Bạn muốn thoát?", loaithongbao.yesno.GetHashCode());
            if (Variable.thongbao == true)
            {

                this.Close();
            }
        }

        private void bton_cauhinh_Click(object sender, EventArgs e)
        {
            mh_dm_company_cauhinhmail frm_cauhinhmail = new mh_dm_company_cauhinhmail();
            frm_cauhinhmail.ShowDialog();
        }

        private void txt_Fax_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Convert.ToInt32(e.KeyChar) != 40 && Convert.ToInt32(e.KeyChar) != 41 && Convert.ToInt32(e.KeyChar) != 45 &&
              Convert.ToInt32(e.KeyChar) != 46 && Convert.ToInt32(e.KeyChar) != 8 && (Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57))
                e.Handled = true;
        }

        private void txt_dienthoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Convert.ToInt32(e.KeyChar) != 40 && Convert.ToInt32(e.KeyChar) != 41 && Convert.ToInt32(e.KeyChar) != 45 &&
              Convert.ToInt32(e.KeyChar) != 46 && Convert.ToInt32(e.KeyChar) != 8 && (Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57))
                e.Handled = true;
        }

        private void BtnEmail_Click(object sender, EventArgs e)
        {
            txtpass.Text = new cpublic().loadformchu_point(200, 200);
        }

        private void txtEmail_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }



    }
}